<html xmlns:th="http://www.thymeleaf.org"><!-- Thymeleaf的命名空间，将静态页面转换为动态的视图 -->
<head>
    <meta content="text/html;charset=UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet"/>

	<style type="text/css">
		.middle {
			float: none;
			display: inline-block;
			vertical-align: middle;
		}
</style>
</head>
<body>

	<div class="container">
		<h2>注册</h2>
		<br/>
		<form action="/" method="POST">
			<div class="row">
				<div class="form-group col-md-6 vertical-middle-sm">
					<label for="email">邮箱</label> 
				    <input type="email" class="form-control" id="email" name="email" aria-describedby="emailHelp">
					<small id="emailHelp" class="form-text text-muted">我们绝不会与其他任何人共享您的电子邮件</small>
				</div>
 
	           <span id="emailError" class="alert alert-danger middle col-xs-4" style="display:none;margin-top:10px;"></span>
			</div>		
		 
			<div class="row">
				<div class="form-group col-md-6">
					<label for="password">密码</label> 
					<input type="password" class="form-control" id="password" name="password">	
				</div>
				<span id="passwordError" class="alert alert-danger middle col-xs-4" style="display:none;margin-top:10px;"></span>
			</div>
			<div class="row">
				<div class="form-group col-md-6">
					<label for="matchingPassword">确认密码</label> 
					<input type="password" class="form-control" id="matchingPassword" name="matchingPassword">
				</div>
				<span id="globalError" class="alert alert-danger middle col-xs-4" style="display:none;margin-top:10px;"></span>
			</div>
				<button type="submit" class="btn btn-primary">提交</button>
		</form>
	</div>

	<script th:src="@{/js/jquery-3.5.1.min.js}" type="text/javascript"></script>
	<script th:src="@{/js/bootstrap.min.js}" type="text/javascript"></script>
	<script th:inline="javascript">
		var serverContext = [[@{/}]];

		$(document).ready(function () {
	 		$('form').submit(function(event) {
				register(event);
			});

			function register(event) { 
				event.preventDefault();
				$(".alert").html("").hide();
				
				var formData= $('form').serialize();
				$.post(serverContext + "user/registration", formData ,function(data){
					if(data.message == "success"){
						window.location.href = serverContext + "successRegister.html";
					}	
				})
				.fail(function(data) {
					if(data.responseJSON.error == "UserAlreadyExist"){
			            $("#emailError").show().html(data.responseJSON.message);
			        }
					else{
						var errors = $.parseJSON(data.responseJSON.message);
						$.each( errors, function( index,item ){
							if (item.field) {
								$("#"+item.field+"Error").show().append(item.defaultMessage+"<br/>");
							}
							else {
								$("#globalError").show().append(item.defaultMessage+"<br/>");
							}
						});
					}
				});
			}
		});
	</script>

</body>
</html>